package main

import (
	"bufio"
	"io"
	"io/ioutil"
	"os"

	"code.google.com/p/go-coreutils/opt"
)

var (
	r = bufio.NewReader(os.Stdin)
)

func readLine() (string, bool) {
	l, isPrefix, err := r.ReadLine()
	line := string(l)
	for err == nil && isPrefix {
		l, isPrefix, err = r.ReadLine()
		line += string(l)
	}
	if err != nil {
		if err != io.EOF {
			panic(err.Error())
		} else {
			return line, true
		}
	}
	return line, false
}

func main() {
	defer func() {
		if e := recover(); e != nil {
			switch err := e.(type) {
			case string:
				os.Stdout.WriteString(os.Args[0] + ": " + err + "\n")
				os.Exit(1)
			default:
				panic(err)
			}
		}
	}()

	opt.Parse("", "", false)

	if len(opt.Args) > 1 {
		os.Stderr.WriteString("usage: sh [options] [script]\n")
		os.Exit(1)
	}

	if len(opt.Args) == 1 {
		progText, err := ioutil.ReadFile(opt.Args[0])
		if err != nil {
			os.Stderr.WriteString("sh: " + err.Error() + "\n")
			os.Exit(1)
		}
		program, err := ParseAll(string(progText))
		if err != nil {
			os.Stderr.WriteString("sh: " + err.Error() + "\n")
			os.Exit(1)
		}
		for _, part := range program {
			panic(part)
		}
	} else {
		for {
			os.Stdout.WriteString("$ ")
			l, eof := readLine()
			if eof {
				os.Exit(0)
			}
			println(l)
		}

	}
}

// The state of our interpreter
type InterpreterState struct {

}

type Command interface {
	run(InterpreterState) InterpreterState
}

type simpleCmd struct {

}

type pipelineCmd struct {

}

type listCmd struct {

}

type compoundCmd struct {

}

type functionDef struct {

}

